package servlet;

import bean.User;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/getuser")
public class GetUsersServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收参数
        String name = req.getParameter("username");

        User user = null;

        switch (name){
            case "马超":
                user = new User(1,"马超",16,"男","骑兵",450.60f);
                break;
            case "诸葛亮":
                user = new User(2,"诸葛亮",17,"男","军师",650.66f);
                break;
            case "黄忠":
                user = new User(3,"黄忠",27,"男","射手",550.00f);
                break;
            case "周瑜":
                user = new User(4,"周瑜",17,"男","水军",556.50f);
                break;
            default:
                user = new User();
                break;
        }

        //javaObject--->json
        JSONObject jsObject = JSONObject.fromObject(user);



        //设置响应时的页面编码
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        writer.print(jsObject);


    }
}
